/*

 */
package com.ohos.connent.accountcloud.sys.modular.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ohos.connent.accountcloud.common.enums.CommonSortOrderEnum;
import com.ohos.connent.accountcloud.common.exception.CommonException;
import com.ohos.connent.accountcloud.common.listener.CommonDataChangeEventCenter;
import com.ohos.connent.accountcloud.common.page.CommonPageRequest;
import com.ohos.connent.accountcloud.sys.core.enums.SysBuildInEnum;
import com.ohos.connent.accountcloud.sys.core.enums.SysDataTypeEnum;

import com.ohos.connent.accountcloud.sys.modular.relation.service.SysRelationService;

import com.ohos.connent.accountcloud.sys.modular.resource.entity.SysPermissions;
import com.ohos.connent.accountcloud.sys.modular.resource.enums.SysResourceCategoryEnum;

import com.ohos.connent.accountcloud.sys.modular.resource.mapper.SysPermissionsMapper;
import com.ohos.connent.accountcloud.sys.modular.resource.param.permissions.SysPermissionsAddParam;
import com.ohos.connent.accountcloud.sys.modular.resource.param.permissions.SysPermissionsEditParam;
import com.ohos.connent.accountcloud.sys.modular.resource.param.permissions.SysPermissionsIdParam;
import com.ohos.connent.accountcloud.sys.modular.resource.param.permissions.SysPermissionsPageParam;
import com.ohos.connent.accountcloud.sys.modular.resource.service.SysMenuService;

import com.ohos.connent.accountcloud.sys.modular.resource.service.SysPermissionsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 模块Service接口实现类
 *
 *
 **/
@Service
public class SysPermissionsServiceImpl extends ServiceImpl<SysPermissionsMapper, SysPermissions> implements SysPermissionsService {

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private SysRelationService sysRelationService;

    @Override
    public Page<SysPermissions> page(SysPermissionsPageParam sysPermissionsPageParam) {
        QueryWrapper<SysPermissions> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysPermissions::getCategory, SysResourceCategoryEnum.PERMISSION.getValue());
        if(ObjectUtil.isNotEmpty(sysPermissionsPageParam.getSearchKey())) {
            queryWrapper.lambda().like(SysPermissions::getTitle, sysPermissionsPageParam.getSearchKey());
        }
        if(ObjectUtil.isAllNotEmpty(sysPermissionsPageParam.getSortField(), sysPermissionsPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(sysPermissionsPageParam.getSortOrder());
            queryWrapper.orderBy(true, sysPermissionsPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(sysPermissionsPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SysPermissions::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SysPermissionsAddParam sysPermissionAddParam) {
        SysPermissions sysPermissions = BeanUtil.toBean(sysPermissionAddParam, SysPermissions.class);
        boolean repeatTitle = this.count(new LambdaQueryWrapper<SysPermissions>().eq(SysPermissions::getCategory,
                SysResourceCategoryEnum.PERMISSION.getValue()).eq(SysPermissions::getTitle, sysPermissions.getTitle())) > 0;
        if(repeatTitle) {
            throw new CommonException("存在重复的模块，名称为：{}", sysPermissions.getTitle());
        }
        sysPermissions.setCode(RandomUtil.randomString(10));
        sysPermissions.setCategory(SysResourceCategoryEnum.PERMISSION.getValue());
        this.save(sysPermissions);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(SysDataTypeEnum.RESOURCE.getValue(), JSONUtil.createArray().put(sysPermissions));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SysPermissionsEditParam sysPermissionsEditParam) {
        SysPermissions sysPermissions = this.queryEntity(sysPermissionsEditParam.getId());
        BeanUtil.copyProperties(sysPermissionsEditParam, sysPermissions);
        boolean repeatTitle = this.count(new LambdaQueryWrapper<SysPermissions>().eq(SysPermissions::getCategory,
                SysResourceCategoryEnum.PERMISSION.getValue()).eq(SysPermissions::getTitle, sysPermissions.getTitle())
                .ne(SysPermissions::getId, sysPermissions.getId())) > 0;
        if(repeatTitle) {
            throw new CommonException("存在重复的权限，名称为：{}", sysPermissions.getTitle());
        }
        this.updateById(sysPermissions);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(SysDataTypeEnum.RESOURCE.getValue(), JSONUtil.createArray().put(sysPermissions));
    }

    @Override
    public void delete(List<SysPermissionsIdParam> sysPermissionsIdParamList) {
        List<String> sysPermissionIdList = CollStreamUtil.toList(sysPermissionsIdParamList, SysPermissionsIdParam::getId);
        if(ObjectUtil.isNotEmpty(sysPermissionIdList)) {
            boolean containsSystemModule = this.listByIds(sysPermissionIdList).stream().map(SysPermissions::getCode)
                    .collect(Collectors.toSet()).contains(SysBuildInEnum.BUILD_IN_MODULE_CODE.getValue());
            if(containsSystemModule) {
                throw new CommonException("不可删除系统内置模块");
            }

        }
    }

    @Override
    public SysPermissions detail(SysPermissionsIdParam sysPermissionsIdParam) {
        return this.queryEntity(sysPermissionsIdParam.getId());
    }

    @Override
    public SysPermissions queryEntity(String id) {
        SysPermissions sysPermissions = this.getById(id);
        if(ObjectUtil.isEmpty(sysPermissions)) {
            throw new CommonException("权限不存在，id值为：{}", id);
        }
        return sysPermissions;
    }
    @Override
    public List<SysPermissions> getSysPermissionsListByIds(List<String> ids){
        return  this.listByIds(ids);
    }
}
